<template>
  <div class="setting-container">
    <!-- 提供了一些默认的内边距 padding -->
    <div class="app-container">
      <el-card v-loading="loading">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="角色管理" name="first">
            <el-button
              type="primary"
              size="small"
              @click="openDialog"
            >+ 新增角色</el-button>
            <el-table :data="roleList">
              <el-table-column type="index" :index="indexMethod" label="序号" />
              <el-table-column prop="name" label="角色名称" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button size="small" type="success" @click="assignPer(row.id)">分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="getRoleDetails(row.id)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="delRole(row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              :current-page="page"
              :page-sizes="[1, 2, 3, 10]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane
            label="公司设置"
            name="second"
          ><!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top: 50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width: 400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width: 400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width: 400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="companyForm.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width: 400px"
                />
              </el-form-item> </el-form></el-tab-pane>
        </el-tabs>

        <el-dialog :title="showTitle" :visible="showDialog" @close="closeDialog">
          <el-form
            ref="roleForm"
            :model="roleForm"
            :rules="rules"
            label-width="90px"
          >
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="角色描述" prop="description">
              <el-input
                v-model="roleForm.description"
                placeholder="请输入角色描述"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button type="primary" @click="addRole">确定</el-button>
            <el-button @click="closeDialog">取消</el-button>
          </template>
        </el-dialog>
      </el-card>
      <!-- 分配权限的弹层 -->
      <el-dialog title="分配权限" :visible="showAssignDialog" @close="closeAssignDialog">
        <el-tree
          :data="permissionList"
          :props="{ label: 'name' }"
          :default-expand-all="true"
          :show-checkbox="true"
          :check-strictly="true"
        />
        <template #footer>
          <div style="text-align: right;">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  reqAddRole,
  reqDelRole,
  reqGetRoleDetails,
  reqGetRoleList,
  reqUpdateRoleDetails
} from '@/api/setting'
import { reqGetCompanyById } from '@/api/company'
import { mapState } from 'vuex'
import { reqGetPermissionList } from '@/api/permission'
import { transListToTree } from '@/utils'
export default {
  name: 'Setting',
  data() {
    return {
      activeName: 'first',
      page: 1,
      pagesize: 3,
      roleList: [],
      total: 0,
      loading: false,
      showDialog: false,
      showAssignDialog: false,
      permissionList: [],
      roleForm: {
        name: '',
        description: ''
      },
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      roleDetails: {},
      title: '',
      rules: {
        name: [
          {
            required: true,
            message: '角色名称不能为空',
            trigger: ['blur', 'change']
          }
        ],
        description: [
          {
            required: true,
            message: '角色描述不能为空',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.roleForm.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event)
    },
    async getRoleList() {
      this.loading = true
      const { data } = await reqGetRoleList(this.page, this.pagesize)
      console.log(data)
      const { rows, total } = data
      this.roleList = rows
      this.total = total
      this.loading = false
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.page = 1
      this.getRoleList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.getRoleList()
    },
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    delRole(id) {
      this.$confirm('此操作会永久删除角色，是否继续？', '提示', {
        type: 'warning'
      })
        .then(async() => {
          const res = await reqDelRole(id)
          console.log(res)
          this.$message.success(res.message)
          if (this.roleList.length === 1 && this.page > 1) {
            this.page--
          }
          this.getRoleList()
        })
        .catch(() => {
          console.log('取消')
        })
    },
    openDialog() {
      this.showDialog = true
    },
    closeDialog() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
      this.title = ''
      this.roleForm = {
        name: '',
        description: ''
      }
    },
    addRole() {
      this.$refs.roleForm.validate(async(flag) => {
        if (!flag) return
        if (this.roleForm.id) {
          const res = await reqUpdateRoleDetails(
            this.roleForm.id,
            this.roleForm
          )
          console.log(res)
          this.$message.success(res.message)
        } else {
          const res = await reqAddRole(this.roleForm)
          console.log(res)
          this.$message.success(res.message)
        }
        this.getRoleList()
        this.closeDialog()
      })
    },
    async getRoleDetails(id) {
      const { data } = await reqGetRoleDetails(id)
      console.log(data)
      this.roleForm = data
      this.openDialog()
      console.log(this.roleForm)
    },
    async getCompanyInfo() {
      const { data } = await reqGetCompanyById(this.userInfo.companyId)
      this.companyForm = data
    },
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    async getPermissionList() {
      const { data } = await reqGetPermissionList()
      // console.log(data)
      this.permissionList = transListToTree(data, '0')
      // console.log(this.list)
    },
    assignPer(id) {
      this.getPermissionList()
      this.showAssignDialog = true
    }
  }
}
</script>
<style scoped></style>
